/************************************************************************************/
/*  Program name CAPFAIMP_DIST_HIST.sql                                        	    */
/*  Creater:  NIP Karen (PCCW - UniHub)                                         	*/
/*************   History   *************************                                */
/* 16 JAN, 2006   NIP Karen         First created                                   */
/************************************************************************************/
SET SERVEROUTPUT ON SIZE 1000000;

DECLARE
	lv_Prog_ID		VARCHAR2(100)	:=	'CAPFAIMP_DIST_HIST';

	lv_Scc_Count	NUMBER	:=	0;
	lv_Err_Count	NUMBER	:=	0;
	lv_Err_Msg		VARCHAR2(500)	:=	'No Error';

	CURSOR Cur_F IS
	SELECT
		*
	FROM
		CRST_FA_DIST_HIST;
	
	lv_Next_Seq_ID		NUMBER;
	lv_COA_ID			NUMBER;

BEGIN
	UPDATE
		FA_DISTRIBUTION_HISTORY
	SET	
		BOOK_TYPE_CODE	=	CAPBRIMP_MAPPING.RenameStr(SUBSTR(BOOK_TYPE_CODE,1,4), BOOK_TYPE_CODE)
	WHERE BOOK_TYPE_CODE IN
		(
		SELECT 
			BOOK_TYPE_CODE
		FROM 
			CRST_FA_DIST_HIST
		);
	
	FOR C1 IN Cur_F LOOP
		BEGIN
			SELECT	FA_DISTRIBUTION_HISTORY_S.NextVal
			INTO	lv_Next_Seq_ID
			FROM	DUAL;

			INSERT	INTO CRST_FA_DIST_HIST_MAP	VALUES
			(
			C1.DISTRIBUTION_ID,   
			lv_Next_Seq_ID 
			);
			
			lv_COA_ID	:=	CAPBRIMP_COMMON.GetCOAIDfromBTC(C1.Book_Type_Code);

			INSERT INTO FA_DISTRIBUTION_HISTORY
			VALUES
			(
			lv_Next_Seq_ID,
			C1.BOOK_TYPE_CODE,
			CAPBRIMP_MAPPING.GetAssetIDMapping(C1.ASSET_ID),
			C1.UNITS_ASSIGNED,
			C1.DATE_EFFECTIVE,
			CAPBRIMP_COMMON.GetSegment(lv_COA_ID,C1.CODE_COMBINATION_ID_D),
			C1.LOCATION_ID,
			CAPBRIMP_MAPPING.GetTXNHeaderIDMapping(C1.TRANSACTION_HEADER_ID_IN),
			C1.LAST_UPDATE_DATE,
			CAPBRIMP_COMMON.GetUser(C1.LAST_UPDATED_NAME),
			C1.DATE_INEFFECTIVE,
			C1.ASSIGNED_TO,
			CAPBRIMP_MAPPING.GetTXNHeaderIDMapping(C1.TRANSACTION_HEADER_ID_OUT),
			C1.TRANSACTION_UNITS,
			CAPBRIMP_MAPPING.GetRetirementIDMapping(C1.RETIREMENT_ID),
			C1.LAST_UPDATE_LOGIN
			);
		EXCEPTION
			WHEN OTHERS THEN
				DBMS_OUTPUT.Put_Line(SQLERRM);
				lv_Err_Count	:=	lv_Err_Count + 1;
		END;
		lv_Scc_Count	:=	lv_Scc_Count	+	1;
	END LOOP;
	
	IF	lv_Err_Count	>	0	THEN
		ROLLBACK;
	END IF;

	INSERT INTO CAPCNV_LOG(
		PROG_ID,
		PROCESS_DATE,
		RECORD_PROCESSED,
		RECORD_REJECTED,
		RECORD_EXTRACTED,
		ERR_MSG
	) VALUES (
		lv_Prog_ID,
		SYSDATE,
		lv_Scc_Count,
		lv_Err_Count,
		lv_Scc_Count-lv_Err_Count,
		lv_Err_Msg
	);
	
	COMMIT;
END;
/